<!--
  产值数据统计
-->
<template>
    <div>
        <searchData ref="searchData" :searchData="searchArr" @search="search"></searchData>
        <a-card :bordered="false" style="minHeight: 400px">
            <a-button class="mb12" type="primary" @click="openModal" v-btn-permission="'pm_029_exp_18'">导出公司汇总数据</a-button>
<!--            先敏的-->
            <a-button class="mb12 ml12" type="primary" @click="exportA" v-btn-permission="'pm_029_exp_19'" :loading="loadingS">导出产值快报</a-button>
            <s-table
                    row-key="unitId"
                    ref="table"
                    size="default"
                    :scroll="{x: true}"
                    :columns="columns"
                    :data="loadData"
                    :children-column-name="'childTree'"
                    :alert="true"
                    show-size-changer
                    show-quick-jumper
                    :showPagination="false"
                    :expanded-row-keys="expandedRowKeys"
                    @expand="expandedRowsChange"
            >

                <template slot="unitName" slot-scope="text, record">
                   <template>{{record.unitName}}   </template>
                    <template v-if="record.unitType!=='PD'"> {{record.total}}</template>
                </template>
                <template slot="action" slot-scope="text, record">
                    <a v-if="record.unitType!=='PD'" @click="correctNum(record)">修正人数</a>
                </template>
            </s-table>
        </a-card>
        <a-modal v-model="visible" title="修正人数" width="60%" @ok="ok" @cancel="cancel" :confirmLoading="confirmLoading"
                 okText="提交"
                 cancelText="关闭">
            <a-form-model
                    ref="adjustPlanForm"
                    :model="form"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 14 }"
            >
                <a-row>
                    <a-col :span="12">
                        <a-form-model-item  label="月份：">
                            <a-input v-model="form.monthly" disabled />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item  label="当月人数（含新生）：" class="requiredFormItem">
                            <a-input-number :max="9999999999" v-model="form.monthlyNumber" :min="0" :precision="0"
                                            placeholder="请输入"
                                            @change="numChange" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item  label="新生人数：">
                            <a-input-number :max="999999999" v-model="form.newStudentNumber" :min="0" :precision="0"
                                            placeholder="请输入"
                                            @change="numChange2" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item  label="当月人数（不含新生）：">
                            <a-input v-model="form.employeeNumber" disabled />
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-modal>
        <!-- 导出 -->
        <a-modal :visible.sync="exportVisible" title="导出" @cancel="exportVisible = false" width="600px">
            <a-row type="flex" :gutter="12">
                <a-col :span="24" style="display: flex; align-items: center">
                  <div style="width: 60px;text-align: right">年</div>
                    <a-date-picker mode="year" placeholder="请选择" v-model="year"
                                   format="YYYY"
                                   valueFormat="YYYY"
                                   :open="yearOpen"
                                   @openChange="openChange"
                                   @panelChange="panelChange"></a-date-picker>
                </a-col>
            </a-row>
            <div slot="footer" class="btn_box">
                <!-- 关闭 -->
                <a-button  @click="exportVisible = false">关闭</a-button>
                <a-button type="primary" :loading="loadingSB"  @click="exportAll">导出</a-button>
            </div>
        </a-modal>
    </div>
</template>

<script>
  import { queryOutputValueStatistics, correctedPersonNumberStatistics, planOutputValueexcelFourExport, planOutputValueexcelExport } from '@/api/project/productionRecords'
  import {getOneOrgUsers} from "@/api/commons"
  import { STable } from '@/components'
  import OrgTreeSelect from '@/components/OrgTreeSelect/index'
  import moment from "moment"
  export default {
    name: 'outputDataStatistics',
    comments: {
      STable
    },
    data() {
      return {
          month: '',
          loadingS:false,
          loadingSB: false,
          exportVisible:false,
        confirmLoading: false,
        visible: false,
        form: {
          monthly: "",
          employeeNumber: "",
          newStudentNumber: "",
          monthlyNumber: ""
        },
        expandedRowKeys: [],
        searchArr: [
          {
            name: '所属单位',
            valueKey: 'searchQuery',
            type: OrgTreeSelect,
          },
          {
            name: '项目状态',
            value: 'statusSet',
            type: 'selectMode',
            data: [
              {
                value:1,
                label: "施工准备阶段"
              },
              {
                value:2,
                label: "在建"
              },
              {
                value:3,
                label: "停工"
              },
              {
                value:4,
                label: "停缓建"
              },
              {
                value:5,
                label: "维保期"
              },
              {
                value:6,
                label: "完结"
              }
            ]
          },
          {
            name: '月度',
            value: 'monthly',
            type: 'month',
          },
          {
            name: '月度确权产值完成率（%）',
            value: 'monthConfirmOutputCompletionRate',
            type: 'select',
            data: [
              {
                value:85,
                label: "低于85%"
              },
            ]
          },
          {
            name: '年度产值完成率（%）',
            value: 'yearOutputCompletionRateStruggle',
            type: 'select',
            data: [
              {
                value:25,
                label: "低于25%"
              },
              {
                value:50,
                label: "低于50%"
              },
              {
                value:75,
                label: "低于75%"
              },
              {
                value:1,
                label: "低于100%"
              },
            ]
          },
          {
            name: '年度人均产值完成率（%）',
            value: 'yearPerOutputCompletionRateStruggle',
            type: 'select',
            data: [
              {
                value:25,
                label: "低于25%"
              },
              {
                value:50,
                label: "低于50%"
              },
              {
                value:75,
                label: "低于75%"
              },
              {
                value:1,
                label: "低于100%"
              },
            ]
          },
        ],
        columns: [
          {
            title: '项目名称',
            dataIndex: 'unitName',
            ellipsis: true,
            width: 260,
            scopedSlots: { customRender: 'unitName' }
          },
          {
            title: '项目状态',
            width: 100,
            dataIndex: 'projectStatus'
          },

          {
            title: '月度',
            dataIndex: 'monthly',
            width: 120,
          },
          {
            title: '年度产值目标(底线)(亿元)',
            dataIndex: 'yearOutputBaseline',
            width: 200
          },
          {
            title: '年度产值目标(目标)(亿元)',
            width: 200,
            dataIndex: 'yearOutputTarget'
          },
          {
            title: '年度产值目标(奋斗)(亿元)',
            width: 200,
            dataIndex: 'yearOutputStruggle'
          },
          {
            title: '年度产值完成率（%）',
            dataIndex: 'yearOutputCompletionRateStruggle',
            width: 200
          },
          {
            title: '年度人均产值完成率（%）',
            width: 220,
            dataIndex: 'yearPerOutputCompletionRateStruggle'
          },
          {
            title: '本月计划产值（亿元）',
            width: 180,
            dataIndex: 'thisMonthPlanOutput'
          },
          {
            title: '本月实际产值（亿元）',
            width: 180,
            dataIndex: 'thisMonthActualOutput'
          },
          {
            title: '本月确权产值（亿元）',
            width: 180,
            dataIndex: 'thisMonthConfirmOutput'
          },
          {
            title: '月度确权产值完成率（%）',
            width: 220,
            dataIndex: 'monthConfirmOutputCompletionRate'
          },
          {
            title: '本月确权人均产值（万元）',
            width: 220,
            dataIndex: 'thisMonthConfirmPerOutput'
          },
          {
            title: '自年初累计实际产值（亿元）',
            width: 220,
            dataIndex: 'yearActualOutput'
          },
          {
            title: '自年初累计确权产值（亿元）',
            width: 220,
            dataIndex: 'yearConfirmOutput'
          },
          {
            title: '开工累计实际产值（亿元）',
            width: 220,
            dataIndex: 'actualTotalOutput'
          },
          {
            title: '开工累计确权产值（亿元）',
            width: 220,
            dataIndex: 'confirmTotalOutput'
          },
          {
            title: '月度实际产值完成率（%）',
            width: 220,
            dataIndex: 'monthActualOutputCompletionRate'
          },
          {
            title: '年度产值序时完成率（%）',
            width: 220,
            dataIndex: 'yearPerOutputChrCompletionRateStruggle'
          },
          {
            title: '人数（不含新生）',
            width: 160,
            dataIndex: 'employeeNumber'
          },
          {
            title: '新生人数',
            width: 100,
            dataIndex: 'newStudentNumber'
          },
          {
            title: '本月实际人均产值（万元）',
            width: 220,
            dataIndex: 'thisMonthActualPerOutput'
          },
          {
            title: '自年初累计实际人均产值(万元)',
            width: 240,
            dataIndex: 'yearActualPerOutput'
          },
          {
            title: '自年初累计确权人均产值(万元)',
            width: 240,
            dataIndex: 'yearConfirmPerOutput'
          },
          {
            title: '人均产值目标(底线-目标-奋斗)(万元)',
            width: 320,
            dataIndex: 'perOutputTarget'
          },
            {
                title: '年度人均产值序时完成率（%）',
                width: 220,
                dataIndex: 'yearPerOutputChrCompletionRate'
            },
          {
            title: '操作',
            dataIndex: 'action',
            width: '170px',
            fixed: 'right',
            scopedSlots: { customRender: 'action' }
          },
        ],
        queryParam: {
          monthly: moment(new Date()).format("YYYY-MM")
        },
        currentMonth: '',
          year: '',
          yearOpen: false
      }
    },
    mounted() {
      this.currentMonth = moment(new Date()).format("YYYY-MM")
      this.$nextTick(()=>{
        this.$refs.searchData.form.setFieldsValue({monthly: this.currentMonth})
      })
    },
    methods: {
        openModal() {
            this.exportVisible = true
        },
        openChange(status) {
            if (status) {
                this.yearOpen = true
            }
        },
        panelChange(value) {

            const year = moment(value).format('YYYY')
            this.yearOpen = false
            this.year = year
            console.log(year)
        },
        exportA() {
            if(this.$userInfo().currentPost.code == 'PD') {
                this.$message.warning('您无权限导出')
                return
            }
            this.loadingS = true
            let data = {
                month: this.queryParam.monthly,
                orgId: this.$userInfo().currentPost.id
            }
            planOutputValueexcelFourExport(data).then(res=>{
                const blob = new Blob([res.data])
                const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
                const downloadElement = document.createElement('a')
                const href = window.URL.createObjectURL(blob) // 创建下载的链接
                downloadElement.href = href
                downloadElement.download = filename
                document.body.appendChild(downloadElement)
                downloadElement.click() //点击下载
                document.body.removeChild(downloadElement) //下载完成移除元素
                window.URL.revokeObjectURL(href) //释放blob对象
                this.loadingS = false
                this.exportVisible = false
            }).catch(()=>{
                this.loadingS = false
            })
        },
        exportAll() {
            if(!this.year) {
                this.$message.warning('请选择年')
                return
            }
            this.loadingSB = true
            let data = {
                year: this.year,
                orgId: this.$userInfo().currentPost.id
            }
            planOutputValueexcelExport(data).then(res=>{
                const blob = new Blob([res.data])
                const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
                const downloadElement = document.createElement('a')
                const href = window.URL.createObjectURL(blob) // 创建下载的链接
                downloadElement.href = href
                downloadElement.download = filename
                document.body.appendChild(downloadElement)
                downloadElement.click() //点击下载
                document.body.removeChild(downloadElement) //下载完成移除元素
                window.URL.revokeObjectURL(href) //释放blob对象
                this.loadingSB = false
                this.exportVisible = false
            }).catch(()=>{
                this.loadingSB = false
            })
        },
      ok() {
        let vm = this;
        if(this.form.employeeNumber==='') {
          this.$message.warning("请填写完所有必填项信息")
          return
        }
        this.confirmLoading = true
        this.$confirm({
          title: '提示',
          content: '请确认是否要修正人数？',
          onOk() {
            correctedPersonNumberStatistics(vm.form).then(res=>{
              vm.confirmLoading = false
              if(res.data.code===200) {
                vm.$message.success('提交成功')
                vm.$refs.table.refresh(true)
                vm.cancel()
              }
            }).catch(()=>{
              vm.confirmLoading = false
            })
          },
          onCancel() {
            vm.confirmLoading = false
          }
        });

      },
      cancel(){
        this.form = {
            id: "",
            monthly: "",
            employeeNumber: "",
            newStudentNumber: "",
            monthlyNumber: ""
        }
        this.visible = false
      },
      numChange() {
        this.form.monthlyNumber = this.form.employeeNumber - this.form.newStudentNumber
      },
      numChange2() {
        if(this.form.newStudentNumber>this.form.employeeNumber) {
          this.form.newStudentNumber = this.form.employeeNumber
        }
        this.form.monthlyNumber = this.form.employeeNumber - this.form.newStudentNumber
      },
      async loadData(parameter){
        try {
          const {
            data: { treeVO }
          } = await queryOutputValueStatistics(this.queryParam)
          return Promise.resolve({
            data: treeVO ? [treeVO] : []
          })
        } catch (error) {
          console.log(error)
          return Promise.reject(error)
        }
      },
      search(val) {
        this.queryParam = val;
        if(!this.queryParam.monthly) {
          this.queryParam.monthly =  this.currentMonth
          this.$nextTick(()=>{
            this.$refs.searchData.form.setFieldsValue({monthly: this.currentMonth})
          })
        }
        this.$refs.table.refresh(true)
      },
      expandedRowsChange(expanded, record) {
        if (expanded) {
          this.expandedRowKeys.push(record.unitId)
        } else {
          this.expandedRowKeys.splice(
            this.expandedRowKeys.findIndex((el) => el === record.unitId),
            1
          )
        }
      },
      correctNum(row) {
        this.visible = true
        this.form.monthly = row.monthly
        this.form.id = row.id
        if(!row.employeeNumber) {
          this.getOneOrgUsers(row.unitId)
        } else {
          this.form.monthlyNumber = row.employeeNumber || 0
          this.form.newStudentNumber = row.newStudentNumber || 0
          this.form.employeeNumber = this.form.monthlyNumber +  this.form.newStudentNumber
        }
      },
      getOneOrgUsers(orgId) {
        let data = {
          "and": true,
          "orgId": orgId,
          "orgType": "2",
          "pageNumber": 1,
          "pageSize": 10
        }
        getOneOrgUsers(data).then(res=>{
            this.form.employeeNumber = res.data.total
            this.form.monthlyNumber = res.data.total
        })
      }
    }
  }
</script>